package integral

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"
)

type IntegralWalletDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewIntegralWalletDao(ctx context.Context, svcCtx *svc.ServiceContext) *IntegralWalletDao {
	return &IntegralWalletDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// CreateWallet -根据用户Id创建积分钱包
func (l *IntegralWalletDao) CreateWallet(userId int32, tx *ent.Tx) (*ent.HzIntegralWallet, error) {
	integralWalletInfo, err := tx.HzIntegralWallet.Create().
		SetUserID(int64(userId)).
		SetCreatedAt(time.Now().Unix()).
		SetUpdateAt(time.Now().Unix()).
		Save(l.ctx)
	if err != nil {
		return nil, err
	}
	return integralWalletInfo, nil
}

// IntegralWalletConditionsOnly - 根据体条件查询单个积分钱包记录
func (l *IntegralWalletDao) IntegralWalletConditionsOnly(conditions []predicate.HzIntegralWallet) (*ent.HzIntegralWallet, error) {
	integralWalletInfo, err := l.svcCtx.Orm.HzIntegralWallet.
		Query().
		Where(conditions...).
		Only(l.ctx)
	if err != nil {
		return nil, err
	}
	return integralWalletInfo, nil
}

// UpdateIntegralWallet -更新用户积分钱包
func (l *IntegralWalletDao) UpdateIntegralWallet(tx *ent.Tx, wallet *ent.HzIntegralWallet) error {
	clientDao := l.svcCtx.Orm.HzIntegralWallet
	if tx != nil {
		clientDao = tx.HzIntegralWallet
	}
	_, err := clientDao.UpdateOneID(wallet.ID).
		SetWalletActiveBalance(wallet.WalletActiveBalance).
		SetUpdateAt(time.Now().Unix()).
		Save(l.ctx)
	if err != nil {
		return err
	}
	return nil
}
